package tracing

import (
	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"
	"io"
	"net/http"
)

type Parser struct {
	propagator *jaeger.TextMapPropagator
}

var parser *Parser

func NewRequestWithTrace(req *http.Request, method, url string, body io.Reader) (*http.Request, error) {
	sc, err := parser.propagator.Extract(opentracing.HTTPHeadersCarrier(req.Header))
	if err != nil {
		return nil, err
	}

	newreq, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	err = parser.propagator.Inject(sc, opentracing.HTTPHeadersCarrier(newreq.Header))
	if err != nil {
		return nil, err
	}

	return newreq, nil
}

func NewParser() *Parser {
	p := &Parser{}
	h := jaeger.HeadersConfig{}
	h.ApplyDefaults()
	text := jaeger.NewTextMapPropagator(&h, *jaeger.NewNullMetrics())
	p.propagator = text

	return p
}

func init() {
	parser = NewParser()
}
